module AboutYou
  module SDK
    module Model
      ###
      # This class represents a products result model
      ###
      class ProductsResult
        include AbstractModel

        # Array of not found product ids
        attr_accessor :ids_not_found
        # String page hash
        attr_accessor :page_hash
        # Array of errors
        attr_accessor :errors
        # Array of instances of AboutYou::SDK::Model::Product
        attr_accessor :products

        ###
        # This method is used for creating an instance of this class by a json_object.
        #
        # * *Args*    :
        #   - +json_object+ -> the json_object received from the api
        #   - +factory+ -> instance of AboutYou::SDK::Factory::DefaultModelFactory
        #
        # * *Returns* :
        #   - Instance of AboutYou::SDK::Model::ProductsResult
        ###
        def self.create_from_json(json_object, factory)
          products_result = new

          products_result.page_hash = json_object['page_hash'] ? json_object['page_hash'] : nil
          products_result.errors = []
          products_result.ids_not_found = []
          products_result.products = {}

          if json_object['ids']
            json_object['ids'].each do |key, json_product|
              if json_product['error_code']
                products_result.ids_not_found.push(key)
                products_result.errors.push(json_product)
                next
              end
              products_result.products[Integer(key)] = factory.create_product(
                json_product
              )
            end
          end

          products_result
        end
      end
    end
  end
end
